<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2019/3/27
 * Time: 13:30
 */
namespace Modules\Service\Logic;
use App\Models\Address;
use App\Models\Attachments;
use App\Models\Goods;
use App\Models\Logistics;
use App\Models\Pay;
use App\Models\ShopOrder;
use App\Models\ShopOrderDetail;
use App\Models\User;
use App\Models\UserCoupon;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ShopOrderLogic extends BaseLogic
{
    //创建订单
    public static function orderAdd($userId,$addressId,$orderGoodsList,$couponId,$payMethod,$openid,$version){
        try{
            //查询用户
            $userData = User::find($userId);
            if (!$userData)return fail(1014,"用户不存在");
            //查询商品
            $goodsData = Goods::where("id",$orderGoodsList['goods_id'])->first();
            if (!$goodsData)return fail(1021,"找不到商品");
            //查询收货地址
            $addressData = Address::find($addressId);
            if (!$addressData)return fail(1018,"无效的地址");
            //生成订单号
            $orderSn = orderSn();
            //查询优惠券
            $coupon_amount = 0;
            if ($couponId){
                $couponData = (new UserCoupon())->query()->where('id',$couponId)->where("user_id",$userId)->where('status',1)->first();
                if ($couponData){
                    $coupon_amount = $couponData->amount;
                    $couponData->status = 4;
                    $couponData->save();
                }else{
                    return fail(1022,"优惠券不可用,请重新选择");
                }
            }
            //计算商品总价
            if (array_key_exists("sku_id",$orderGoodsList)){
                $goods_amount = $orderGoodsList['sku_price']*$orderGoodsList['goods_num'];
            }else{
                $goods_amount = $orderGoodsList['price']*$orderGoodsList['goods_num'];
            }
            //计算订单总价
            $order_amount = $goods_amount-$coupon_amount;
            //收货地址
            $address = $addressData->procince.$addressData->city.$addressData->district.$addressData->address;
            //开启事务
            DB::beginTransaction();

            //生成订单
            $order = new ShopOrder();
            $order->user_id = $userId;
            $order->order_sn = $orderSn;
            $order->goods_amount = $goods_amount;
            $order->order_amount = $order_amount;
            $order->coupon_amount = $coupon_amount;
            $order->coupon_id = $couponId;
            $order->username = $addressData->username;
            $order->phone = $addressData->phone;
            $order->address = $address;
            $order->order_status = 0;
            $order->order_time = Carbon::now();
            $order->save();

            //生成订单商品数据
            $orderGoods = new ShopOrderDetail();
            $orderGoods->order_id = $order->id;
            $orderGoods->order_sn = $order->order_sn;
            $orderGoods->goods_id = $orderGoodsList["goods_id"];
            $orderGoods->class_id = $goodsData->class_id;
            $orderGoods->class_name = $goodsData->class_name;
            $orderGoods->goods_name = $orderGoodsList['goods_name'];
            $orderGoods->image = $orderGoodsList['image'];
            $orderGoods->price = $orderGoodsList['price'];
            $orderGoods->num = $orderGoodsList['goods_num'];
            $orderGoods->sku_id = $orderGoodsList['sku_id'];
            $orderGoods->sku_name = $orderGoodsList['sku_name'];
            $orderGoods->sku_price = $orderGoodsList['sku_price'];
            $orderGoods->amount = $orderGoodsList['sku_price']*$orderGoodsList['goods_num'];
            $orderGoods->save();

            //创建支付
            $pay = new Pay();
            $pay->payment_method = $payMethod;
            $pay->user_id = $userId;
            $pay->pay_sn = Pay::makeGouwuPaySn();
            $pay->amount = $order_amount;
            $pay->save();

            //修改订单
            $order->pay_id = $pay->id;
            $order->save();

            $response = [
                'order_id' => $order->id,
                'order_sn' => $orderSn,
                'payment_method' => $payMethod,
                'pay_info' => null,
            ];

            $response['pay_info'] = '';
            $response['weixin_app'] = null;
            if ($payMethod == 'alipay') {
                $response['pay_info'] = Pay::alipay($pay);
            }
            if ($payMethod == 'weixin_app') {
                $response['weixin_app'] = Pay::weixinApp($pay,$version);
            }
            if ($payMethod == 'weixin') {
                $response['weixin'] = Pay::weixin($pay, $openid);
            }

            DB::commit();
            return success($response);
        }catch (\Exception $e){
            Log::error($e);
            DB::rollBack();
            return fail(500,"系统错误");
        }
    }

    //订单再次支付
    public static function orderPay($userId,$orderId,$payMethod,$openid,$version){
        try{
            //获取用户信息
            $userData = User::find($userId);
            if (!$userData)return fail(1014,"用户不存在");
            //查询订单
            $orderData = ShopOrder::find($orderId);
            if (!$orderData)return fail(1025,"找不到此订单");
            //更改支付方式
            $pay = $orderData->pay;
            $pay->payment_method = $payMethod;
            $pay->save();

            $response = [
                'order_id' => $orderData->id,
                'payment_method' => $payMethod,
                'pay_info' => null,
            ];
            //支付序号
            if ($pay->pay_sn) {
                $pay->pay_sn = Pay::makeYouKaPaySN();
            }
            $response['pay_info'] = '';
            $response['weixin_app'] = null;
            if ($payMethod == 'alipay') {
                $response['pay_info'] = Pay::alipay_num($pay);
            }
            if ($payMethod == 'weixin_app') {
                $response['weixin_app'] = Pay::weixinApp_num($pay,$version);
            }
            if ($payMethod == 'weixin') {
                $response['weixin'] = Pay::weixin_num($pay, $openid);
            }
            return success($response);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    //订单列表
    public static function orderList($userId,$status,$page,$limit){
        try{
            //查询用户
            $userData = User::find($userId);
            if (!$userData)return fail(1014,"用户不存在");
            //判断状态值
            if ($status=='all'){
                $orderData = ShopOrder::where("user_id",$userId)
                    ->orderBy('id','desc')
                    ->select('id','order_sn','goods_amount','order_amount','pay_amount',"order_status","order_time","pay_time","send_time","finished_time","order_type","shipping_company","shipping_code")
                    ->get();
            }else{
                $orderData = ShopOrder::where("user_id",$userId)
                    ->where("order_status",$status)
                    ->orderBy('id','desc')
                    ->select('id','order_sn','goods_amount','order_amount','pay_amount',"order_status","order_time","pay_time","send_time","finished_time","order_type","shipping_company","shipping_code")
                    ->get();
            }
            $orderArray = [];
            if ($orderData->count()>0){
                foreach ($orderData as $item){
                    $orderTxt = '';

                    switch ($item['order_status']){
                        case -1:
                            $orderTxt = '已取消';
                            break;
                        case 0:
                            $orderTxt = '待付款';
                            break;
                        case 1:
                            $orderTxt = '待发货';
                            break;
                        case 2:
                            $orderTxt = '待收货';
                            break;
                        case 3:
                            $orderTxt = '已完成';
                            break;
                    }
                    if (in_array($item['order_status'],[2,3])){
                        $wuliu = Logistics::where("code",$item['shipping_company'])->first();
                        if ($wuliu) {
                            $item['shipping_company_name'] = $wuliu->name;
                            $item['shipping_url'] = "https://m.kuaidi100.com/app/query/?com={$item['shipping_company']}&nu={$item['shipping_code']}";
                        }
                    }
                    $detailData = ShopOrderDetail::where("order_id",$item['id'])->select("goods_id","goods_name","image","price","num","sku_name","sku_price","amount")->first();
                    if ($detailData){
                        //切割图片
                        if ($detailData['image']!='') {
                            $exp = explode(',', $detailData['image']);
                            $imageData = Attachments::find($exp[0]);
                            if ($imageData){
                                $detailData['image'] = $imageData->file_url;
                            }
                        }
                        if ($item['order_type']=='oil_card'){
                            $detailData['sku_price'] = $item['goods_amount'];
                            if (preg_match('/^1\d{18}$/',$detailData['goods_name'],$arr)){
                                $detailData['oilcard_type'] = "中石化";
                            }elseif(preg_match('/^9\d{15}$/',$detailData['goods_name'],$arr)){
                                $detailData['oilcard_type'] = "中石油";
                            }
                        }
                        $item['goods'] = $detailData;
                        $item['order_text'] = $orderTxt;
                    }
                    if ($item['order_type']=='oil_card' && $item['order_status']==0){
                        continue;
                    }else {
                        $orderArray[] = $item;
                    }
                }
            }
            $orderCount = count($orderArray);
            return success(['count'=>$orderCount,'data'=>array_slice($orderArray,($page-1)*$limit,$limit)]);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统异常");
        }
    }

    //订单详情
    public static function orderDetail($order_id){
        try{
            //查询订单
            $orderData = ShopOrder::where('id',$order_id)->select('id','order_sn','goods_amount','order_amount','pay_amount','coupon_amount','username','phone','address','shipping_company','shipping_code','order_status','order_time','pay_time','send_time','finished_time','order_type')->first();
            if ($orderData){
                //查询订单商品
                $detailData = ShopOrderDetail::where("order_id",$order_id)->select('id','goods_name','image','sku_name','num','price','sku_price')->first();
                //切割图片
                if ($detailData['image']!='') {
                    $exp = explode(',', $detailData['image']);
                    $imageData = Attachments::find($exp[0]);
                    if ($imageData){
                        $detailData['image'] = $imageData->file_url;
                    }
                }
                if ($orderData['order_type']=='oil_card'){
                    $detailData['sku_price'] = $orderData['goods_amount'];
                    if (preg_match('/^1\d{18}$/',$detailData['goods_name'],$arr)){
                        $detailData['oilcard_type'] = "中石化";
                    }elseif(preg_match('/^9\d{15}$/',$detailData['goods_name'],$arr)){
                        $detailData['oilcard_type'] = "中石油";
                    }
                }
                $orderData['detail'] = $detailData;
                $orderTxt = '';
                if ($orderData['order_status']==0){
                    $orderTxt = "待付款";
                }elseif($orderData['order_status']==1){
                    $orderTxt = "待发货";
                }elseif ($orderData['order_status']==2){
                    $orderTxt = "待收货";
                }elseif ($orderData['order_status']==3){
                    $orderTxt = "交易成功";
                }elseif ($orderData['order_status']==-1){
                    $orderTxt = "已取消";
                }
                $orderData['order_text'] = $orderTxt;
                if (in_array($orderData['order_status'],[2,3])){
                    $wuliu = Logistics::where("code",$orderData['shipping_company'])->first();
                    if ($wuliu) {
                        $orderData['shipping_company_name'] = $wuliu->name;
                        $orderData['shipping_url'] = "https://m.kuaidi100.com/app/query/?com={$orderData['shipping_company']}&nu={$orderData['shipping_code']}";
                    }
                }

            }
            return success($orderData);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统异常");
        }
    }

    //取消订单
    public static function orderClose($orderId){
        try{
            //查询订单
            $orderData = ShopOrder::find($orderId);
            if (!$orderData)return fail(1025,"订单不存在");
            if ($orderData->order_status>0)return fail(1045,"订单状态异常");
            //修改订单状态
            $orderData->order_status = -1;
            $orderData->save();

            if ($orderData->coupon_id){
                $coupon = UserCoupon::find($orderData->coupon_id);
                if ($coupon){
                    $coupon->status = 1;
                    $coupon->save();
                }
            }
            return success();
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统异常");
        }
    }

    //确认收货
    public static function orderFinish($orderId){
        try{
            //查询订单
            $orderData = ShopOrder::find($orderId);
            if (!$orderData)return fail(1025,"订单不存在");
            //修改订单状态
            $orderData->order_status = 3;
            $orderData->finished_time = Carbon::now();
            $orderData->save();
            return success();
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统异常");
        }
    }

    /**
     * 删除订单
     * @param $orderId
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public static function orderDelete($orderId){
        try{
            $orderData = ShopOrder::find($orderId);
            if (!$orderData)return fail(1025,"订单不存在");
            if ($orderData->order_status!=-1){
                return fail(1045,"订单状态异常,无法删除");
            }
            $orderData->delete();
            return success();
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }
}